package homework6.exp2;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test2 {


    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        Document document = documentBuilder.parse("src/phone.xml");
        Element brand = document.createElement("Brand");
        brand.setAttribute("name","MOTO");
        Element type = document.createElement("Type");
        type.setAttribute("name","A1680");
        //添加父子关系
        brand.appendChild(type);
        //通过根结点查询PhoneInfo标签
        Element phoneIfo = (Element)document.getElementsByTagName("PhoneInfo").item(0);
        //把brand 标签添加到PhoneInfo
        phoneIfo.appendChild(brand);
        //保存文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        //设置编码
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        StreamResult result = new StreamResult(new FileOutputStream("src/phone.xml"));
        transformer.transform(domSource,result);

    }
}
